package com.lianniu.web.staff.service.impl;

import com.alibaba.fastjson.JSON;
import com.lianniu.redis.RedisUtils;
import com.lianniu.web.base.BaseResult;
import com.lianniu.web.baseService.user.model.FrontUserVo;
import com.lianniu.web.baseService.user.model.UserLoginLogVo;
import com.lianniu.web.baseService.user.service.IUserLoginLogService;
import com.lianniu.web.constants.ErrorCode;
import com.lianniu.web.constants.UserErrorCode;
import com.lianniu.web.staff.dao.StaffDao;
import com.lianniu.web.staff.service.StaffService;
import com.lianniu.web.staff.vo.Staff;
import com.lianniu.web.util.MD5Util;
import com.lianniu.web.util.StringUtil;
import com.lianniu.web.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017-05-16.
 */
@Service
public class StaffServiceImpl implements StaffService {
    private final static int TIME = 3600 * 24;
    Logger logger = LoggerFactory.getLogger(StaffServiceImpl.class);
    @Autowired
    IUserLoginLogService userLoginLogService;

    @Autowired
    StaffDao staffDao;


    @Override
    @Transactional
    public BaseResult login(HttpServletRequest request, String username, String userpasswd,
                            String codeUuid, String code, int times) {
        logger.info("login begin.");
        logger.info("parameter username:" + username);
        logger.info("parameter userpasswd:" + userpasswd);
        logger.info("parameter codeUuid:" + codeUuid);
        logger.info("parameter code:" + code);
        logger.info("parameter times:" + times);
        logger.info("login checkParameter begin.");
        if (StringUtil.isEmpty(username)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                    ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(userpasswd)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                    ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(codeUuid)) {
            return BaseResult.fail(ErrorCode.IsNullRetCode, ErrorCode.IsNullRetInfo);
        }
        if (times > 3) {

            if (StringUtil.isEmpty(code)) {
                return BaseResult.fail(ErrorCode.IsNullRetCode, ErrorCode.IsNullRetInfo);
            }

            if (!RedisUtils.get("codeUuid:" + codeUuid).equalsIgnoreCase(code)) {
                return BaseResult.fail(UserErrorCode.CaptchaErrorRetCode,
                        UserErrorCode.CaptchaErrorRetInfo);
            }
        }
        logger.info("login checkParameter end.");
        FrontUserVo frontUserVo = new FrontUserVo();
        frontUserVo.setUserName(username);
        logger.info("login getUser beigin.");

        Staff staff = staffDao.selectByLoginName(username);
        if (staff == null) {
            return BaseResult.fail(UserErrorCode.UserNotExistErrorRetCode,
                    UserErrorCode.UserNotExistErrorRetInfo);
        }
        logger.info("login checkuserpasswd begin.");
        if (!MD5Util.checkPassword(userpasswd, staff.getLoginPassword())
                || !staff.getLoginName().equals(username)) {
            return BaseResult.fail(UserErrorCode.UserOrPassErrorRetCode,
                    UserErrorCode.UserOrPassErrorRetInfo);
        }
        logger.info("userCheckFail checkuserpasswd end.");
        String token = UUIDUtil.getUUID();
        RedisUtils.set("usrMgr:" + token, username);
        RedisUtils.set("usrMgr:" + username, token);
        RedisUtils.expire("usrMgr:" + token, TIME);
        RedisUtils.expire("usrMgr:" + username, TIME);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("token", token);
        result.put("username", staff.getLoginName());
        result.put("userid", staff.getId());
        logger.info("userCheckFail return:" + JSON.toJSONString(result));
        logger.info("login end.");
        logger.info("login addLog begin.");

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        UserLoginLogVo userLoginLogVo = new UserLoginLogVo();
        userLoginLogVo.setLogInTime(new Date());
        userLoginLogVo.setLoginIp(ip);
        userLoginLogVo.setStaffId(staff.getId());
        userLoginLogVo.setAddTime(userLoginLogVo.getLogInTime());
        userLoginLogService.addUserLoginLog(userLoginLogVo);
        result.put("logId", userLoginLogVo.getId());
        logger.info("login addLog end.");
        return BaseResult.success(result);
    }

    @Override
    public BaseResult insertSelective(Staff record) {
        return BaseResult.success(this.staffDao.insertSelective(record));
    }

    @Override
    public BaseResult selectByPrimaryKey(String id) {
        Staff staff = this.staffDao.selectByPrimaryKey(id);
        return BaseResult.success(staff);
    }

    @Override
    public BaseResult selectByLoginName(String loginName) {
        return null;
    }

    @Override
    public BaseResult updateByPrimaryKeySelective(Staff record) {
        this.staffDao.updateByPrimaryKeySelective(record);
        return BaseResult.success();
    }
}
